package com.mg.plugin.agrometeorology.model;

import com.mg.model.Model;
import com.mg.model.Param;
import com.mg.model.Port;
import com.mg.plugin.agrometeorology.common.StationDataType;
import com.mg.plugin.agrometeorology.entity.StationData;
import com.mg.pluginexample2.ModuleBase;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 玉米/大豆蚜虫
 */
public class AphisMatsmuraModel extends ModuleBase {
    public AphisMatsmuraModel(int nID) {
        super(nID);
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alOutputPort.add(new Port(this, Port.Type.Unknown));
    }

    public String GetGroupName() {
        return "灾害制作";
    }

    public String GetName() {
        return "玉米/大豆蚜虫";
    }

    public String GetDescription() {
        return "吉林灾害制作";
    }

    public boolean OnAttach(Port portFrom, Port portTo) {
        try {
            int i = FindPort(portFrom, false);
            if (i != -1) {
                return true;
            }
            i = FindPort(portTo, true);
            if (i == -1) {
                return false;
            }

            ArrayList<Param> alParam = new ArrayList<Param>();
            portFrom.GetModule().GetOutputParam(portFrom, alParam);

            if (alParam.size() != 1) {
                return false;
            }

            if (alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof ArrayList)) {
                return false;
            }
            if (i == 0) {
                m_inputForecastList = (List<String>) alParam.get(0).m_objValue;
            }
            if (i == 1) {
                m_inputRealityList = (List<String>) alParam.get(0).m_objValue;
            }

            portTo.SetType(portFrom.GetType());
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean OnDetach(Port portFrom, Port portTo) {
        if (!super.OnDetach(portFrom, portTo))
            return false;
        try {
            int i = FindPort(portTo, true);
            if (i == -1)
                return true;
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    //用于 参数->XML 等
    public int GetParam(ArrayList<Param> alParam) {
        try {
            super.GetParam(alParam);
            alParam.add(new Param("StationId", m_strStationId, "站点ID对应字段", "StationId", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Date", m_strDate, "时间对应字段", "Date", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Precipitation", m_strRain, "降水对应字段", "Precipitation", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("OldPrecipitation", m_strOldRain, "常年降水对应字段", "OldPrecipitation", "参数匹配", Param.EditType.Default));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return alParam.size();
    }

    public boolean OnParamChanged(ArrayList<Param> alParam, int nIndex, Object objValue) {
        return super.OnParamChanged(alParam, nIndex, objValue);
    }

    //用于 XML->参数 等
    public int SetParam(final ArrayList<Param> alParam) {
        int i = super.SetParam(alParam);
        try {
            m_strStationId = (String) alParam.get(i++).m_objValue;
            m_strDate = (String) alParam.get(i++).m_objValue;
            m_strRain = (String) alParam.get(i++).m_objValue;
            m_strOldRain = (String) alParam.get(i++).m_objValue;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return i;
    }

    public int GetOutputParam(Port port, ArrayList<Param> alParam) {
        int i = FindPort(port, false);
        if (i == -1) {
            System.out.println("Post Is Null");
            return 0;
        }

        alParam.add(new Param("ResultString", m_listCSV));
        return alParam.size();
    }

    @SuppressWarnings("static-access")
    public boolean Execute() {

        m_listCSV.clear();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String head = "StationNum,Data,Time";
        String type = "String,Double,String";
        m_listCSV.add(head);
        m_listCSV.add(type);

        Map<String, List<StationData>> stationDataList = new HashMap<String, List<StationData>>();

        if (m_inputRealityList != null && m_inputRealityList.size() > 0) {
            String realHeader = m_inputRealityList.get(0);
            if (!verifyHeader(realHeader)) {
                m_model.OutputLog(Model.LogLevel.Error, "Header Can Not Match!");
                return false;
            } else {

                formatStationData(m_inputRealityList, realHeader, stationDataList);
            }

        }

        if (m_inputForecastList != null && m_inputForecastList.size() > 0) {
            String foreHeader = m_inputForecastList.get(0);
            if (!verifyHeader(foreHeader)) {
                m_model.OutputLog(Model.LogLevel.Error, "Header Can Not Match!");
                return false;
            } else {
                formatStationData(m_inputForecastList, foreHeader, stationDataList);
            }

        }


        try {
            for (String stationId : stationDataList.keySet()) {
                float g = calcDisasterLevel(stationDataList.get(stationId));
                m_listCSV.add(stationId + "," + g + "," + sdf.format(new Date()));
            }
        } catch (ParseException e) {
            m_model.OutputLog(Model.LogLevel.Error, "ParseException!");
            e.printStackTrace();
            return false;
        }
        OnParamChanged();
        return true;
    }

    private void formatStationData(List<String> inputRealityList, String realHeader, Map<String, List<StationData>> stationDataList) {
        int realStationIndex = findDataIndex(realHeader, m_strStationId);
        int realDateIndex = findDataIndex(realHeader, m_strDate);
        int realRainIndex = findDataIndex(realHeader, m_strRain);
        int realOldRainIndex = findDataIndex(realHeader, m_strOldRain);
        for (int i = 2; i < inputRealityList.size(); i++) {
            String stationId = inputRealityList.get(i).split(",")[realStationIndex];
            StationData stationData = new StationData(inputRealityList.get(i), realStationIndex, realDateIndex, realRainIndex, realOldRainIndex, StationDataType.APHIS_GLYCINES);

            if (stationDataList.keySet().contains(stationId)) {
                stationDataList.get(stationId).add(stationData);
            } else {
                List<StationData> dataList = new ArrayList<StationData>();
                dataList.add(stationData);
                stationDataList.put(stationId, dataList);
            }
        }
    }


    /**
     * 表头检验
     *
     * @param realHeader 实况数据表头
     * @return
     */
    private boolean verifyHeader(String realHeader) {

        if (realHeader.contains(m_strDate) && realHeader.contains(m_strStationId)) {
            if (realHeader.contains(m_strOldRain) && realHeader.contains(m_strRain)) {
                return true;
            }
        }
        return false;
    }

    private float calcDisasterLevel(List<StationData> stationDatas) throws ParseException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        float rain = 0;
        float oldRain = 0;
        for (StationData data : stationDatas) {
            rain += data.getRain();
            oldRain += data.getOldRain();
        }
        return (rain - oldRain) / oldRain;
    }

    private int findDataIndex(String realHeader, String strRain) {

        String[] data = realHeader.split(",");
        for (int i = 0; i < data.length; i++) {
            if (data[i].equalsIgnoreCase(strRain)) {
                return i;
            }
        }
        return -1;
    }

    private List<String> m_inputForecastList = new ArrayList<String>();
    private List<String> m_inputRealityList = new ArrayList<String>();
    private List<String> m_listCSV = new ArrayList<String>();

    private String m_strStationId;
    private String m_strDate;
    private String m_strRain;
    private String m_strOldRain;
}
